package com.lvyq.wx.util;

import com.alibaba.fastjson.JSONObject;
import com.lvyq.constant.WeChatOauthConstant;
import com.lvyq.util.HttpRequestUtil;
import com.lvyq.wx.model.SNSUserInfo;
import com.lvyq.wx.model.WeixinOauth2Token;

/**
 * @version 1.0
 * @description: 微信网页授权相关工具类
 * @author: lvyq
 * @date: 2020/9/15 11:32
 */
public class SNSAuthUtil {

    /**
     * @description: code换取openid，access_token
     * @author: lvyq
     * @date: 2020/9/15 11:34
     * @version 1.0
     */
    public static WeixinOauth2Token getOauth2AccessToken(String appId, String appSecret, String code) {
        WeixinOauth2Token wat = null;
        // 拼接请求地址
        String requestUrl = WeChatOauthConstant.OAUTH2_ACCESS_TOKEN;
        requestUrl = requestUrl.replace("APPID", appId).replace("SECRET", appSecret).replace("CODE", code);
        // 获取网页授权凭证
        JSONObject jsonObject = HttpRequestUtil.httpsRequest(requestUrl, "GET", null);
        if (null != jsonObject) {
            try {
                wat = new WeixinOauth2Token();
                wat.setAccessToken(jsonObject.getString("access_token"));
                wat.setExpiresIn(jsonObject.getInteger("expires_in"));
                wat.setRefreshToken(jsonObject.getString("refresh_token"));
                wat.setOpenId(jsonObject.getString("openid"));
                wat.setScope(jsonObject.getString("scope"));

            } catch (Exception e) {
                wat = null;
                int errorCode = jsonObject.getInteger("errcode");
                String errorMsg = jsonObject.getString("errmsg");
                System.out.print("获取网页授权凭证失败 errcode:{} errmsg:{}" + errorCode + errorMsg);
            }
        }
        return wat;

    }


    /**
     * @description: 刷新access_token
     * @author: lvyq
     * @date: 2021/2/20 13:16
     * @version 1.0
     */
    public static JSONObject refreshToken(String appId, String refreshToken) {
        String requestUrl = WeChatOauthConstant.OAUTH2_REFRESH_TOKEN;
        requestUrl = requestUrl.replace("APPID", appId).replace("REFRESH_TOKEN", refreshToken);
        JSONObject jsonObject = HttpRequestUtil.httpsRequest(requestUrl, "GET", null);
        return jsonObject;
    }


    /**
     * @description: 检测access_token是否有效-网页授权凭证access_token
     * @author: lvyq
     * @date: 2021/2/20 13:24
     * @version 1.0
     */
    public static JSONObject checkSnsAuth(String openid, String accessToken) {
        String requestUrl = WeChatOauthConstant.SNS_AUTH;
        requestUrl = requestUrl.replace("OPENID", openid).replace("ACCESS_TOKEN", accessToken);
        JSONObject jsonObject = HttpRequestUtil.httpsRequest(requestUrl, "GET", null);
        return jsonObject;
    }


    /**
     * @description: 获取微信用户基本信息
     * @author: lvyq
     * @date: 2021/2/20 13:47
     * @version 1.0
     */
    public static SNSUserInfo getSnsUserInfo(String openId, String accessToken) {
        SNSUserInfo snsUserInfo = null;
        String requestUrl = WeChatOauthConstant.SNS_USER_INFO;
        requestUrl = requestUrl.replace("OPENID", openId).replace("ACCESS_TOKEN", accessToken);
        JSONObject jsonObject = HttpRequestUtil.httpsRequest(requestUrl, "GET", null);

        if (null != jsonObject) {
            try {
                snsUserInfo = new SNSUserInfo();
                // 用户的标识
                snsUserInfo.setOpenId(openId);
                // 昵称
                snsUserInfo.setNickname(jsonObject.getString("nickname"));
                // 性别（1是男性，2是女性，0是未知）
                snsUserInfo.setSex(jsonObject.getInteger("sex"));
                // 用户所在国家
                snsUserInfo.setCountry(jsonObject.getString("country"));
                // 用户所在省份
                snsUserInfo.setProvince(jsonObject.getString("province"));
                // 用户所在城市
                snsUserInfo.setCity(jsonObject.getString("city"));
                // 用户头像
                snsUserInfo.setHeadImgUrl(jsonObject.getString("headimgurl"));
                // 用户特权信息
                //snsUserInfo.setPrivilegeList(JSONArray.toList(jsonObject.getJSONArray("privilege"), List.class));
                //获取unionid
                snsUserInfo.setUnionid(jsonObject.getString("unionid"));
            } catch (Exception e) {
                int errorCode = jsonObject.getInteger("errcode");
                String errorMsg = jsonObject.getString("errmsg");
                System.out.println("获取用户信息失败 errcode:{} errmsg:{}" + errorCode + errorMsg);
                e.printStackTrace();
            }
        }
        return snsUserInfo;
    }
}

